package com.ucode.hrm.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.IdcardUtil;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;
import com.ucode.hrm.controller.service.ApiHrmDataPermissionService;
import com.ucode.hrm.controller.service.ApiHrmExcelHandleService;
import com.ucode.hrm.service.HrmAttendanceConfigService;
import com.ucode.hrm.service.HrmCustomerCompanyService;
import com.ucode.hrm.service.HrmCustomerProjectService;
import com.ucode.hrm.service.HrmEmployeeService;
import com.ucode.model.hrm.HrmAttendanceConfig;
import com.ucode.model.hrm.HrmCustomerCompany;
import com.ucode.model.hrm.HrmCustomerProject;
import com.ucode.model.hrm.HrmEmployee;
import com.ucode.model.hrm.convert.HrmEmployeeConvert;
import com.ucode.model.hrm.enums.HrmEmploymentTypeEnum;
import com.ucode.model.hrm.enums.HrmExcelTemplateEnum;
import com.ucode.model.hrm.form.HrmEmployResignationForm;
import com.ucode.model.hrm.form.HrmEmployeeForm;
import com.ucode.model.hrm.vo.HrmEmployeeVO;
import com.ucode.springboot.starter.operatelog.core.annotations.UcodeOperateLogBp;
import com.ucode.ssm.busiconf.service.SysConfigService;
import com.ucode.tool.annotation.DataPermission;
import com.ucode.tool.annotation.NeedLogin;
import com.ucode.tool.base.Paginator;
import com.ucode.tool.base.ResponseResult;
import com.ucode.tool.base.enums.GlobalResultCodeEnum;
import com.ucode.tool.base.enums.SexEnum;
import com.ucode.tool.exception.UcodeServiceException;
import com.ucode.tool.poi.excel.ExcelUtils;
import com.ucode.tool.util.CollectionUtils;
import com.ucode.tool.util.IdentifyUtils;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.enums.ParameterIn;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.Size;
import java.io.IOException;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.*;

@Tag(name = "管理后台 - 人力资源系统 - 员工")
@RestController
@RequestMapping("/hrm/employee")
@Validated
public class HrmEmployeeController {
    private static final Log log = LogFactory.get();

    @Resource
    private HrmCustomerProjectService customerProjectService;
    @Resource
    private HrmCustomerCompanyService  customerCompanyService;
    @Resource
    private HrmEmployeeService employeeService;
    @Resource
    private ApiHrmDataPermissionService apiHrmDataPermissionService ;
    @Resource
    private ApiHrmExcelHandleService apiHrmExcelHandleService;
    @Resource
    private HrmAttendanceConfigService hrmAttendanceConfigService;
    @Resource
    private SysConfigService sysConfigService;

    // 到期提醒时间
    private static final String hrm_ec_employee_time = "hrm_ec_employee_time";

    @GetMapping("/all-page-list")
    @Operation(summary = "获得分页列表")
    @PreAuthorize("@usfs.hasPermission('hrm:employee:query')")
    public ResponseResult<Paginator<HrmEmployeeVO>> pageListByAll(
            @Schema(description = "客户公司编码") @RequestParam(value = "customerCompanyId",required = false) Long customerCompanyId,
            @Schema(description = "客户项目编码") @RequestParam(value = "projectId",required = false) Long projectId,
            @Schema(description = "员工名称") @RequestParam(value = "realName",required = false) String realName,
            @Schema(description = "手机号") @RequestParam(value = "phone",required = false) String phone,
            @Schema(description = "性别") @RequestParam(value = "gender",required = false) Integer gender,
            @Schema(description = "编制类型") @RequestParam(value = "employmentType",required = false) Integer employmentType,
            @Schema(description = "创建时间区间",example = "[2022-07-01 00:00:00,2022-07-01 23:59:59]")  @RequestParam(value = "createTimeInterval",required = false) LocalDateTime[] createTimeInterval,
            @Schema(description = "页码",example="1") @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
            @Schema(description = "每页记录数",example="5") @RequestParam(value = "pageSize", defaultValue = "5") Integer pageSize){

        Map<String,Object> condition = new HashMap<>();
        if(StrUtil.isNotBlank(realName))
            condition.put("realName", StrUtil.concat(true,"%", realName,"%"));
        if(StrUtil.isNotBlank(phone))
            condition.put("phone", StrUtil.concat(true,"%", phone,"%"));
        if(ArrayUtil.isNotEmpty(createTimeInterval) && createTimeInterval.length == 2){
            condition.put("startTime",createTimeInterval[0]);
            condition.put("endTime",createTimeInterval[1]);
        }
        condition.put("customerCompanyId",customerCompanyId);
        condition.put("projectId",projectId);
        condition.put("gender",gender);
        condition.put("employmentType",employmentType);
        condition.put("deltag",false);
        return ResponseResult.success(pageList(condition,pageNum,pageSize));
    }

    @GetMapping("/page-list")
    @Operation(summary = "获得在职分页列表")
    @PreAuthorize("@usfs.hasPermission('hrm:employee:query')")
    @DataPermission(permissions={"hrm:employee:query"})
    public ResponseResult<Paginator<HrmEmployeeVO>> pageList(
            @Schema(description = "客户公司编码") @RequestParam(value = "customerCompanyId",required = false) Long customerCompanyId,
            @Schema(description = "客户项目编码") @RequestParam(value = "projectId",required = false) Long projectId,
            @Schema(description = "员工名称") @RequestParam(value = "realName",required = false) String realName,
            @Schema(description = "手机号") @RequestParam(value = "phone",required = false) String phone,
            @Schema(description = "性别") @RequestParam(value = "gender",required = false) Integer gender,
            @Schema(description = "编制类型") @RequestParam(value = "employmentType",required = false) Integer employmentType,
            @Schema(description = "创建时间区间",example = "[2022-07-01 00:00:00,2022-07-01 23:59:59]")  @RequestParam(value = "createTimeInterval",required = false) LocalDateTime[] createTimeInterval,
            @Schema(description = "页码",example="1") @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
            @Schema(description = "每页记录数",example="5") @RequestParam(value = "pageSize", defaultValue = "5") Integer pageSize){

        Map<String,Object> condition = new HashMap<>();
        if(StrUtil.isNotBlank(realName))
            condition.put("realName", StrUtil.concat(true,"%", realName,"%"));
        if(StrUtil.isNotBlank(phone))
            condition.put("phone", StrUtil.concat(true,"%", phone,"%"));
        if(ArrayUtil.isNotEmpty(createTimeInterval) && createTimeInterval.length == 2){
            condition.put("startTime",createTimeInterval[0]);
            condition.put("endTime",createTimeInterval[1]);
        }
        condition.put("customerCompanyId",customerCompanyId);

        Set<Long> customerProjectIds = apiHrmDataPermissionService.getCurrentUserCustomerProjectIdsByDataPermission();
        //没有可查看的数据
        if(ObjUtil.isNotNull(customerProjectIds) && customerProjectIds.size() == 0){
            return ResponseResult.success(new Paginator<>());
        }

        //没有权限查看指定项目的数据
        if(ObjUtil.isNotNull(projectId) && ObjUtil.isNotNull(customerProjectIds) && !customerProjectIds.contains(projectId)){
            throw new UcodeServiceException(GlobalResultCodeEnum.UN_DATA_PERMISSION);
        }
        condition.put("projectIds",customerProjectIds);
        condition.put("projectId",projectId);
        condition.put("gender",gender);
        if(ObjUtil.isNotNull(employmentType)){
            condition.put("employmentType",employmentType);
        }else {
            condition.put("employmentTypeList",CollUtil.toList(HrmEmploymentTypeEnum.INTERN.getCode(),HrmEmploymentTypeEnum.PROBATION.getCode(),HrmEmploymentTypeEnum.FULL_TIME.getCode()));
        }
        condition.put("deltag",false);
        return ResponseResult.success(pageList(condition,pageNum,pageSize));
    }

    @GetMapping("/resign-page-list")
    @Operation(summary = "获得离职员工分页列表")
    @PreAuthorize("@usfs.hasPermission('hrm:resign-employee:query')")
    @DataPermission(permissions={"hrm:resign-employee:query"})
    public ResponseResult<Paginator<HrmEmployeeVO>> pageListByResign(
            @Schema(description = "客户公司编码") @RequestParam(value = "customerCompanyId",required = false) Long customerCompanyId,
            @Schema(description = "客户项目编码") @RequestParam(value = "projectId",required = false) Long projectId,
            @Schema(description = "员工名称") @RequestParam(value = "realName",required = false) String realName,
            @Schema(description = "手机号") @RequestParam(value = "phone",required = false) String phone,
            @Schema(description = "性别") @RequestParam(value = "gender",required = false) Integer gender,
            @Schema(description = "创建时间区间",example = "[2022-07-01 00:00:00,2022-07-01 23:59:59]")  @RequestParam(value = "createTimeInterval",required = false) LocalDateTime[] createTimeInterval,
            @Schema(description = "页码",example="1") @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
            @Schema(description = "每页记录数",example="5") @RequestParam(value = "pageSize", defaultValue = "5") Integer pageSize){

        Map<String,Object> condition = new HashMap<>();
        if(StrUtil.isNotBlank(realName))
            condition.put("realName", StrUtil.concat(true,"%", realName,"%"));
        if(StrUtil.isNotBlank(phone))
            condition.put("phone", StrUtil.concat(true,"%", phone,"%"));
        if(ArrayUtil.isNotEmpty(createTimeInterval) && createTimeInterval.length == 2){
            condition.put("startTime",createTimeInterval[0]);
            condition.put("endTime",createTimeInterval[1]);
        }
        condition.put("customerCompanyId",customerCompanyId);

        Set<Long> customerProjectIds = apiHrmDataPermissionService.getCurrentUserCustomerProjectIdsByDataPermission();
        //没有可查看的数据
        if(ObjUtil.isNotNull(customerProjectIds) && customerProjectIds.size() == 0){
            return ResponseResult.success(new Paginator<>());
        }

        //没有权限查看指定项目的数据
        if(ObjUtil.isNotNull(projectId) && ObjUtil.isNotNull(customerProjectIds) && !customerProjectIds.contains(projectId)){
            throw new UcodeServiceException(GlobalResultCodeEnum.UN_DATA_PERMISSION);
        }
        condition.put("projectIds",customerProjectIds);
        condition.put("projectId",projectId);
        condition.put("gender",gender);
        condition.put("employmentType",HrmEmploymentTypeEnum.LEFT.getCode());
        condition.put("deltag",false);
        return ResponseResult.success(pageList(condition,pageNum,pageSize));
    }


    @GetMapping("/apply-page-list")
    @Operation(summary = "获得分页列表")
    @PreAuthorize("@usfs.hasPermission('hrm:apply-employee:query')")
    public ResponseResult<Paginator<HrmEmployeeVO>> pageListByApply(
            @Schema(description = "员工名称") @RequestParam(value = "realName",required = false) String realName,
            @Schema(description = "手机号") @RequestParam(value = "phone",required = false) String phone,
            @Schema(description = "性别") @RequestParam(value = "gender",required = false) Integer gender,
            @Schema(description = "创建时间区间",example = "[2022-07-01 00:00:00,2022-07-01 23:59:59]")  @RequestParam(value = "createTimeInterval",required = false) LocalDateTime[] createTimeInterval,
            @Schema(description = "页码",example="1") @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
            @Schema(description = "每页记录数",example="5") @RequestParam(value = "pageSize", defaultValue = "5") Integer pageSize){

        Map<String,Object> condition = new HashMap<>();
        if(StrUtil.isNotBlank(realName))
            condition.put("realName", StrUtil.concat(true,"%", realName,"%"));
        if(StrUtil.isNotBlank(phone))
            condition.put("phone", StrUtil.concat(true,"%", phone,"%"));
        if(ArrayUtil.isNotEmpty(createTimeInterval) && createTimeInterval.length == 2){
            condition.put("startTime",createTimeInterval[0]);
            condition.put("endTime",createTimeInterval[1]);
        }
        condition.put("employmentType",HrmEmploymentTypeEnum.APPLY.getCode());
        condition.put("gender",gender);
        condition.put("deltag",false);
        return ResponseResult.success(pageList(condition,pageNum,pageSize));
    }


    @GetMapping("/project-release-page-list")
    @Operation(summary = "获得项目释放的员工分页列表")
    @PreAuthorize("@usfs.hasPermission('hrm:project-release-employee:query')")
    public ResponseResult<Paginator<HrmEmployeeVO>> pageListByProjectRelease(
            @Schema(description = "员工名称") @RequestParam(value = "realName",required = false) String realName,
            @Schema(description = "手机号") @RequestParam(value = "phone",required = false) String phone,
            @Schema(description = "性别") @RequestParam(value = "gender",required = false) Integer gender,
            @Schema(description = "创建时间区间",example = "[2022-07-01 00:00:00,2022-07-01 23:59:59]")  @RequestParam(value = "createTimeInterval",required = false) LocalDateTime[] createTimeInterval,
            @Schema(description = "页码",example="1") @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
            @Schema(description = "每页记录数",example="5") @RequestParam(value = "pageSize", defaultValue = "5") Integer pageSize){

        Map<String,Object> condition = new HashMap<>();
        if(StrUtil.isNotBlank(realName))
            condition.put("realName", StrUtil.concat(true,"%", realName,"%"));
        if(StrUtil.isNotBlank(phone))
            condition.put("phone", StrUtil.concat(true,"%", phone,"%"));
        if(ArrayUtil.isNotEmpty(createTimeInterval) && createTimeInterval.length == 2){
            condition.put("startTime",createTimeInterval[0]);
            condition.put("endTime",createTimeInterval[1]);
        }

        condition.put("projectId",0L);
        condition.put("gender",gender);
        condition.put("employmentTypeList",CollUtil.toList(HrmEmploymentTypeEnum.INTERN.getCode(),HrmEmploymentTypeEnum.PROBATION.getCode(),HrmEmploymentTypeEnum.FULL_TIME.getCode()));
        condition.put("deltag",false);
        condition.put("applyFlag",false);
        return ResponseResult.success(pageList(condition,pageNum,pageSize));
    }

    @GetMapping("/ec-page-list")
    @Operation(summary = "获得满期在职员工分页列表")
    @PreAuthorize("@usfs.hasPermission('hrm:ec-employee:query')")
    @DataPermission(permissions={"hrm:ec-employee:query"})
    public ResponseResult<Paginator<HrmEmployeeVO>> pageListByEc(
            @Schema(description = "场景类型:1、即将到期或已到期项目 2、即将到期项目 3、已到期项目") @RequestParam(value = "sceneType",required = true) Integer sceneType,
            @Schema(description = "客户公司编码") @RequestParam(value = "customerCompanyId",required = false) Long customerCompanyId,
            @Schema(description = "客户项目编码") @RequestParam(value = "projectId",required = false) Long projectId,
            @Schema(description = "员工名称") @RequestParam(value = "realName",required = false) String realName,
            @Schema(description = "手机号") @RequestParam(value = "phone",required = false) String phone,
            @Schema(description = "性别") @RequestParam(value = "gender",required = false) Integer gender,
            @Schema(description = "创建时间区间",example = "[2022-07-01 00:00:00,2022-07-01 23:59:59]")  @RequestParam(value = "createTimeInterval",required = false) LocalDateTime[] createTimeInterval,
            @Schema(description = "页码",example="1") @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
            @Schema(description = "每页记录数",example="5") @RequestParam(value = "pageSize", defaultValue = "5") Integer pageSize){

        Map<String,Object> condition = new HashMap<>();
        if(StrUtil.isNotBlank(realName))
            condition.put("realName", StrUtil.concat(true,"%", realName,"%"));
        if(StrUtil.isNotBlank(phone))
            condition.put("phone", StrUtil.concat(true,"%", phone,"%"));
        if(ArrayUtil.isNotEmpty(createTimeInterval) && createTimeInterval.length == 2){
            condition.put("startTime",createTimeInterval[0]);
            condition.put("endTime",createTimeInterval[1]);
        }
        condition.put("customerCompanyId",customerCompanyId);

        Set<Long> customerProjectIds = apiHrmDataPermissionService.getCurrentUserCustomerProjectIdsByDataPermission();
        //没有可查看的数据
        if(ObjUtil.isNotNull(customerProjectIds) && customerProjectIds.size() == 0){
            return ResponseResult.success(new Paginator<>());
        }

        //没有权限查看指定项目的数据
        if(ObjUtil.isNotNull(projectId) && ObjUtil.isNotNull(customerProjectIds) && !customerProjectIds.contains(projectId)){
            throw new UcodeServiceException(GlobalResultCodeEnum.UN_DATA_PERMISSION);
        }
        condition.put("projectIds",customerProjectIds);
        condition.put("projectId",projectId);
        condition.put("gender",gender);
        condition.put("employmentTypeList",CollUtil.toList(HrmEmploymentTypeEnum.INTERN.getCode(),HrmEmploymentTypeEnum.PROBATION.getCode(),HrmEmploymentTypeEnum.FULL_TIME.getCode()));

        condition.put("contractTypeList",CollUtil.toList(1,2));//入职合同和续期合同
        condition.put("sceneType",sceneType);
        if(ObjUtil.equals(sceneType,1) || ObjUtil.equals(sceneType,2)){
            String reminderTimeStr = sysConfigService.getPropertyValue(hrm_ec_employee_time);
            Integer reminderTime = StrUtil.isBlank(reminderTimeStr) ? 10 : Integer.parseInt(reminderTimeStr);
            condition.put("ecTime", LocalDate.now().plusDays(reminderTime));//提前提醒时间
            condition.put("currentDate",LocalDate.now());
        }else {
            condition.put("currentDate",LocalDate.now());
        }


        condition.put("deltag",false);
        return ResponseResult.success(pageList(condition,pageNum,pageSize));
    }


    @GetMapping("/ssp-page-list")
    @Operation(summary = "获得社保待办理分页列表")
    @PreAuthorize("@usfs.hasPermission('hrm:ssp-employee:query')")
    public ResponseResult<Paginator<HrmEmployeeVO>> pageListBySsp(
            @Schema(description = "客户公司编码") @RequestParam(value = "customerCompanyId",required = false) Long customerCompanyId,
            @Schema(description = "客户项目编码") @RequestParam(value = "projectId",required = false) Long projectId,
            @Schema(description = "员工名称") @RequestParam(value = "realName",required = false) String realName,
            @Schema(description = "手机号") @RequestParam(value = "phone",required = false) String phone,
            @Schema(description = "性别") @RequestParam(value = "gender",required = false) Integer gender,
            @Schema(description = "编制类型") @RequestParam(value = "employmentType",required = false) Integer employmentType,
            @Schema(description = "创建时间区间",example = "[2022-07-01 00:00:00,2022-07-01 23:59:59]")  @RequestParam(value = "createTimeInterval",required = false) LocalDateTime[] createTimeInterval,
            @Schema(description = "页码",example="1") @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
            @Schema(description = "每页记录数",example="5") @RequestParam(value = "pageSize", defaultValue = "5") Integer pageSize){

        Map<String,Object> condition = new HashMap<>();
        if(StrUtil.isNotBlank(realName))
            condition.put("realName", StrUtil.concat(true,"%", realName,"%"));
        if(StrUtil.isNotBlank(phone))
            condition.put("phone", StrUtil.concat(true,"%", phone,"%"));
        if(ArrayUtil.isNotEmpty(createTimeInterval) && createTimeInterval.length == 2){
            condition.put("startTime",createTimeInterval[0]);
            condition.put("endTime",createTimeInterval[1]);
        }
        condition.put("customerCompanyId",customerCompanyId);
        condition.put("projectId",projectId);
        condition.put("gender",gender);
        condition.put("employmentType",employmentType);

        condition.put("sspMark", false);
        condition.put("deltag",false);
        condition.put("orderByStr", "order by updatedTime desc");
        return ResponseResult.success(pageList(condition,pageNum,pageSize));
    }

    @GetMapping("/list-simple-page")
    @Operation(summary = "分页获取精简信息列表(没有权限校验，公共查询接口)", description = "主要用于前端的下拉选项")
    @DataPermission(permissions={"hrm:employee:query"})
    public ResponseResult<Paginator<HrmEmployeeVO>> simplePageList(
            @Schema(description = "员工名称") @RequestParam(value = "realName",required = false) String realName,
            @Schema(description = "手机号") @RequestParam(value = "phone",required = false) String phone,
            @Schema(description = "性别") @RequestParam(value = "gender",required = false) Integer gender,
            @Schema(description = "编制类型") @RequestParam(value = "employmentType",required = false) Integer employmentType,
            @Schema(description = "页码",example="1") @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
            @Schema(description = "每页记录数",example="5") @RequestParam(value = "pageSize", defaultValue = "5") Integer pageSize) {

        Map<String,Object> condition = new HashMap<>();
        if(StrUtil.isNotBlank(realName))
            condition.put("realName", StrUtil.concat(true,"%", realName,"%"));
        if(StrUtil.isNotBlank(phone))
            condition.put("phone", StrUtil.concat(true,"%", phone,"%"));

        Set<Long> customerProjectIds = apiHrmDataPermissionService.getCurrentUserCustomerProjectIdsByDataPermission();
        //没有可查看的数据
        if(ObjUtil.isNotNull(customerProjectIds) && customerProjectIds.size() == 0){
            return ResponseResult.success(new Paginator<>());
        }
        condition.put("projectIds",customerProjectIds);

        condition.put("gender",gender);
        condition.put("employmentType",employmentType);
        condition.put("deltag",false);
        condition.put("applyFlag",false);

        return ResponseResult.success(pageList(condition,pageNum,pageSize));
    }

    private Paginator<HrmEmployeeVO> pageList(Map<String,Object> condition, int pageNum, int pageSize) {
        Paginator<HrmEmployee> paginator = employeeService.queryPageForList(condition,pageSize,pageNum);
        Paginator<HrmEmployeeVO> paginatorVO =  HrmEmployeeConvert.INSTANCE.convertPage(paginator);

        if(CollUtil.isNotEmpty(paginatorVO.getList())) {
            Set<Long> customerCompanyIds =   CollectionUtils.convertSet( paginatorVO.getList(),HrmEmployeeVO::getCompanyId);
            Set<Long> projectIds =   CollectionUtils.convertSet( paginatorVO.getList(),HrmEmployeeVO::getProjectId);
            Map<Long, HrmCustomerCompany> customerCompanyMap = customerCompanyService.getMap(customerCompanyIds);
            Map<Long, HrmCustomerProject> projectMap = customerProjectService.getMap(projectIds);
            paginatorVO.getList().forEach(item -> {
                HrmCustomerCompany customerCompany = customerCompanyMap.get(item.getCompanyId());
                if(customerCompany != null)
                    item.setCompanyName(customerCompany.getCompanyName());

                HrmCustomerProject project = projectMap.get(item.getProjectId());
                if(project != null)
                    item.setProjectName(project.getProjectName());
            });
        }

        return paginatorVO;
    }

    @GetMapping("/getById/{id}")
    @Parameter(description="主键ID",name = "id", required = true,in = ParameterIn.PATH,example = "1024")
    @Operation(summary = "主键获得信息")
    @PreAuthorize("@usfs.hasPermission('hrm:employee:query')")
    public ResponseResult<HrmEmployeeVO> getById(@PathVariable(name="id",required=true) Long id){
        HrmEmployee bean = employeeService.validate(id);
        HrmEmployeeVO vo = HrmEmployeeConvert.INSTANCE.convert(bean);
        if(ObjUtil.isNotNull(vo.getCompanyId())){
            HrmCustomerCompany customerCompany = customerCompanyService.selectByPrimaryKey(bean.getCompanyId());
            if(customerCompany != null)
                vo.setCompanyName(customerCompany.getCompanyName());
        }

        if(ObjUtil.isNotNull(vo.getProjectId())){
            HrmCustomerProject project = customerProjectService.selectByPrimaryKey(bean.getProjectId());
            if(project != null)
                vo.setProjectName(project.getProjectName());
        }

        if(ObjUtil.isNotNull(vo.getAttCfgId())){
            HrmAttendanceConfig config = hrmAttendanceConfigService.selectByPrimaryKey(bean.getAttCfgId());
            if(config != null)
                vo.setAttCfgTitle(config.getTitle());
        }else
            vo.setAttCfgId(null);

        return ResponseResult.success(vo);
    }

    @PostMapping("/create")
    @Operation(summary = "创建")
    @PreAuthorize("@usfs.hasPermission('hrm:employee:create')")
    public ResponseResult<Long> create(@Valid @RequestBody HrmEmployeeForm form) {
        HrmEmployee bean = HrmEmployeeConvert.INSTANCE.convert(form);
        bean.setId(IdentifyUtils.getDefaultSnowflakeId());

        if(ObjUtil.isNotNull(bean.getProjectId())){
            HrmCustomerProject project = customerProjectService.validate(bean.getProjectId());
            bean.setProjectId(project.getId());
            bean.setCompanyId(project.getCustomerCompanyId());
        }

        if(StrUtil.isNotBlank(bean.getIdCardNumber())){
            //从身份证中获取出生日期
            bean.setBirthDate(IdcardUtil.getBirthDate(bean.getIdCardNumber()).toLocalDateTime().toLocalDate());
            //根据身份证号码获取籍贯
            bean.setRegisteredResidence(IdcardUtil.getProvinceByIdCard(bean.getIdCardNumber()));
            //根据身份证号码获取性别
            bean.setGender(IdcardUtil.getGenderByIdCard(bean.getIdCardNumber()) == 1 ? SexEnum.MALE.getCode() : SexEnum.FEMALE.getCode());
        }


        Long id = employeeService.insert(bean);
        return id != null ? ResponseResult.success(id) : ResponseResult.failed();
    }

    @PostMapping("/update/{id}")
    @Parameter(description="主键ID",name = "id", required = true,in = ParameterIn.PATH,example = "1024")
    @Operation(summary = "修改")
    @PreAuthorize("@usfs.hasPermission('hrm:employee:update')")
    public ResponseResult<Object> update(@PathVariable(name="id",required=true) Long id,
                                         @Valid @RequestBody HrmEmployeeForm form) {
        HrmEmployee bean = HrmEmployeeConvert.INSTANCE.convert(form);
        bean.setId(id);

        if(ObjUtil.isNotNull(bean.getProjectId())){
            HrmCustomerProject project = customerProjectService.validate(bean.getProjectId());
            bean.setProjectId(project.getId());
            bean.setCompanyId(project.getCustomerCompanyId());
        }

        if(StrUtil.isNotBlank(bean.getIdCardNumber())){
            //从身份证中获取出生日期
            bean.setBirthDate(IdcardUtil.getBirthDate(bean.getIdCardNumber()).toLocalDateTime().toLocalDate());
            //根据身份证号码获取籍贯
            bean.setRegisteredResidence(IdcardUtil.getProvinceByIdCard(bean.getIdCardNumber()));
            //根据身份证号码获取性别
            bean.setGender(IdcardUtil.getGenderByIdCard(bean.getIdCardNumber()) == 1 ? SexEnum.MALE.getCode() : SexEnum.FEMALE.getCode());
        }
        int i = employeeService.update(bean);
        return i > 0 ? ResponseResult.success() : ResponseResult.failed();
    }

    @PostMapping("/resignation")
    @Operation(summary = "离职")
    @PreAuthorize("@usfs.hasPermission('hrm:employee:resignation')")
    public ResponseResult<Long> resignation(@Valid @RequestBody HrmEmployResignationForm form) {
        HrmEmployee bean = new HrmEmployee();
        bean.setId(form.getEmployeeId());
        bean.setResignationDate(form.getResignationDate());
        bean.setResignReason(form.getResignReason());
        bean.setResigType(form.getResigType());
        bean.setEconomic(form.getEconomic());
        bean.setCompensation(form.getCompensation());
        bean.setComFeeTotal(form.getComFeeTotal());
        bean.setComProvideTime(form.getComProvideTime());
        bean.setSspEndTime(form.getSspEndTime());
        bean.setSspMark(false);
        //bean.setEmploymentType(HrmEmploymentTypeEnum.LEFT.getCode());
        int i = employeeService.update(bean);
        return i > 0 ? ResponseResult.success() : ResponseResult.failed();
    }


    @PostMapping("/logic-delete/{id}")
    @Operation(summary = "转移到回收站")
    @Parameter(description="主键ID",name = "id", required = true,in = ParameterIn.PATH, example = "1024")
    @PreAuthorize("@usfs.hasPermission('hrm:employee:logic-delete')")
    public ResponseResult<Object> logicDelete(@PathVariable(name="id",required=true) Long id) {
        //逻辑删除
        int i = employeeService.logicDeletePrimaryKey(id);
        return i > 0 ? ResponseResult.success() : ResponseResult.failed();
    }

    @PostMapping("/batch-logic-delete")
    @Operation(summary = "批量转移到回收站")
    @PreAuthorize("@usfs.hasPermission('hrm:employee:logic-delete')")
    public ResponseResult<Boolean> batchLogicDeletePrimaryKey(@Schema(description = "编号集合",requiredMode = Schema.RequiredMode.REQUIRED)
                                                @NotEmpty(message = "编号集合为空")@Size(min = 1,max = 100,message = "编号集合数量为1-100条")
                                                @RequestParam(value = "ids",required = true) List<Long> ids) {
        int i = employeeService.logicDeleteByPrimaryKeys(ids);
        return i > 0 ? ResponseResult.success() : ResponseResult.failed();
    }


    @PostMapping("/project-release")
    @Operation(summary = "项目释放员工")
    @PreAuthorize("@usfs.hasPermission('hrm:employee:project-release')")
    public ResponseResult<Object> projectRelease(@Schema(description = "编号集合",requiredMode = Schema.RequiredMode.REQUIRED)
                                                     @NotEmpty(message = "编号集合为空")@Size(min = 1,max = 100,message = "编号集合数量为1-100条")
                                                     @RequestParam(value = "ids",required = true) List<Long> ids) {

        for(Long id : ids){
            HrmEmployee bean = new HrmEmployee();
            bean.setId(id);
            bean.setProjectId(0L);
            bean.setCompanyId(0L);
            int i = employeeService.update(bean);
        }
        return ResponseResult.success();
    }



    @PostMapping("/project-take")
    @Operation(summary = "项目领走员工")
    @Parameter(description="主键ID",name = "id", required = true,in = ParameterIn.PATH, example = "1024")
    @PreAuthorize("@usfs.hasPermission('hrm:employee:project-take')")
    public ResponseResult<Object> projectTake(@Schema(description = "编号集合",requiredMode = Schema.RequiredMode.REQUIRED)
                                                     @NotEmpty(message = "编号集合为空")@Size(min = 1,max = 100,message = "编号集合数量为1-100条")
                                                     @RequestParam(value = "ids",required = true) List<Long> ids,
                                                     @Schema(description = "项目编号",requiredMode = Schema.RequiredMode.REQUIRED)
                                                     @RequestParam(value = "projectId",required = true) Long projectId) {


        HrmCustomerProject project = customerProjectService.validate(projectId);
        for(Long id : ids){
            HrmEmployee bean = new HrmEmployee();
            bean.setId(id);
            bean.setProjectId(project.getId());
            bean.setCompanyId(project.getCustomerCompanyId());
            int i = employeeService.update(bean);
        }

        return ResponseResult.success();
    }

    @PostMapping("/batch-ssp-mark")
    @Operation(summary = "批量处理社保处理标记")
    @PreAuthorize("@usfs.hasPermission('hrm:employee:ssp-mark')")
    public ResponseResult<Boolean> batchUpdateSspMark(@Schema(description = "编号集合",requiredMode = Schema.RequiredMode.REQUIRED)
                                                          @NotEmpty(message = "编号集合为空")@Size(min = 1,max = 100,message = "编号集合数量为1-100条")
                                                          @RequestParam(value = "ids",required = true) List<Long> ids,
                                                          @Schema(description = "处理标记",requiredMode = Schema.RequiredMode.REQUIRED)
                                                          @RequestParam(value = "sspMark",required = true) Boolean sspMark) {
        int i = employeeService.updateSspMark(ids, sspMark);
        return i > 0 ? ResponseResult.success() : ResponseResult.failed();
    }

    @NeedLogin
    @GetMapping("/export-tpl")
    @Operation(summary = "导出模板")
    @UcodeOperateLogBp(enable = false) //没有记录操作日志的必要
    public void exportTpl(HttpServletResponse response) throws IOException {
        ExcelUtils.write(response, HrmExcelTemplateEnum.EMPLOYEE_TEMPLATE.getName(), HrmExcelTemplateEnum.EMPLOYEE_TEMPLATE.getName(), new HashMap(), new ArrayList<>());
    }


    @PostMapping("/import") // 映射到/api/excel/parse
    @Operation(summary = "导入")
    @PreAuthorize("@usfs.hasPermission('hrm:employee:create')")
    @UcodeOperateLogBp(logArgs = false) //没有记录操作日志的必要
    public ResponseResult<Boolean> importEmployeesData(@RequestParam("file") MultipartFile file) throws Exception {
        apiHrmExcelHandleService.importEmployeesData(file);
        return ResponseResult.success();
    }

}
